package logic

import (
	"context"
	"fmt"
	jwts "go-zero/common/jwt"
	"go-zero/user-jwt/internal/svc"
	"go-zero/user-jwt/internal/types"
	"go-zero/user-jwt/models"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	fmt.Println(req)
	var user models.User
	err = l.svcCtx.DB.Take(&user).Select("username = ?", req.UserName).Error
	fmt.Printf("%v", user)
	if err != nil {
		return &types.LoginResp{
			Token: "token",
		}, err
	}
	auth := l.svcCtx.Config.Auth
	jwtPayload := jwts.JwtPayload{
		user.ID,
		1,
	}
	token, err := jwts.GenToken(jwtPayload, auth.AccessSecret, auth.AccessExpire)
	if err != nil {
		return nil, err
	}
	return &types.LoginResp{
		Token: token,
	}, nil
}
